/**
 * @file zipper.cpp
 * @brief 
 * @author haibo.yang
 * @version 1.0
 * @date 2024-02-28
 * 
 * @copyright Copyright (c) 2023  lgim
 * 
 */
#include "zipper.h"
#include <zip.h>
#include <boost/filesystem.hpp>
#include <stdexcept>

using std::shared_ptr;
using std::string;

namespace record {

Zipper::Zipper (boost::filesystem::path file)
{
	int error;
	INFO("[Zipper] create zip:" << file);
	_zip = zip_open(file.string().c_str(), ZIP_CREATE | ZIP_EXCL, &error);
	if (!_zip) {
		if (error == ZIP_ER_EXISTS) {
			ERROR ("[Zipper] ZIP file already exists" << file);
		}
		ERROR ("[Zipper] could not create ZIP file:" << file << " error number:" << error);
	}
}

#define HAVE_ZIP_FILE_ADD
int Zipper::add (const string name, const string path)
{
	// shared_ptr<string> copy(new string(content));
	// _store.push_back (copy);
    INFO("[Zipper] add to zip name:" << name << ", path:" << path);
	auto source = zip_source_file(_zip, path.c_str(), 0, 0);
	if (!source) {
		ERROR ("[Zipper] could not create ZIP source");
		return -1;
	}

	zip_int64_t index;
#ifdef HAVE_ZIP_FILE_ADD
	if (index = zip_file_add(_zip, name.c_str(), source, ZIP_FL_OVERWRITE|ZIP_FL_ENC_GUESS) == -1) {
#else
	if (index = zip_add(_zip, name.c_str(), source) == -1) {
#endif
		ERROR ("[Zipper] failed to add data to ZIP archive (%1)" << zip_strerror(_zip));
		return -1;
	}

	// Set the file compression level
	if (zip_set_file_compression(_zip, index, ZIP_CM_STORE, 0) < 0) {
        ERROR ("Failed to set file compression: " << zip_strerror(_zip));
        return -1;
    }
	return 0;
}

void Zipper::close ()
{
	if (zip_close(_zip) == -1) {
		ERROR ("[Zipper] failed to close ZIP archive");
	}
	_zip = nullptr;
}

Zipper::~Zipper ()
{
	if (_zip) {
		zip_close(_zip);
	}
}

}